package com.blb.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;

/**
 * AIO模型客户端
 */
public class AIOClient {

    public void sendMessage(String ip,int port,String message) throws IOException, ExecutionException, InterruptedException {
        //创建异步Socket通道
        AsynchronousSocketChannel socketChannel =
                AsynchronousSocketChannel.open();
        //连接服务器
        socketChannel.connect(new InetSocketAddress(ip,port)).get();
        //向服务器发消息
        socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        //读服务器消息
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int len = socketChannel.read(byteBuffer).get();
        if(len != -1){
            String msg = new String(byteBuffer.array(),0,len);
            System.out.println("获得服务器消息：" + msg);
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        new AIOClient().sendMessage("192.168.114.22",9999,"Hello Server");
    }
}
